<template>
  <div class="space-container">
    <!-- 头部 -->
    <div class="header">
      <div class="title-section">
        <el-icon class="icon"><Collection /></el-icon>
        <span class="title">个人空间</span>
        <el-tag type="info" round>{{ papersMessage.total }}</el-tag>
      </div>
      <el-button type="primary" :icon="Plus" @click="handleAdd">新建空间</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
          ref="paperTable"
          :data="papersMessage.list"
          style="width: 100%"
          :row-class-name="tableRowClassName"
          v-loading="loading"
          border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="空间名称" width="600"  align="center">
          <template #default="scope">
            <div class="name-cell">
              <el-icon><Folder /></el-icon>
              <span>{{ scope.row.name || '未命名空间' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建者" width="155" align="center" />
        <el-table-column prop="createdAt" label="创建时间" width="200" align="center" />
        <el-table-column label="操作" width="300" align="center" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)" :icon="Edit">
                编辑
              </el-button>
              <el-button type="success" size="small" @click="handleRename(scope.row)" :icon="EditPen">
                重命名
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)" :icon="Delete">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="params.pageNo"
          v-model:page-size="params.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="params.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
          background />
    </div>

    <!-- 重命名对话框 -->
    <el-dialog
        v-model="renameDialogVisible"
        title="重命名空间"
        width="30%"
        :close-on-click-modal="false">
      <el-form :model="renameForm" label-width="80px">
        <el-form-item label="空间名称" required>
          <el-input v-model="renameForm.name" placeholder="请输入新的空间名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRename" :loading="renameLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Collection, Plus, Folder, Edit, EditPen, Delete } from '@element-plus/icons-vue'
import {deleteForm, getPagedFormList, updateFormName} from '@/api/form.js'
import Formbuild from "@/components/team/formbuild.vue";

const router = useRouter()
const loading = ref(false)
const renameDialogVisible = ref(false)
const renameLoading = ref(false)
const currentRow = ref(null)
const renameForm = reactive({
  name: ''
})

const papersMessage = ref({
  list: [],
  total: 0
})

const params = reactive({
  pageNo: 1,
  pageSize: 5,
  total: 0
})

// 获取表格数据
const queryFormMessage = async () => {
  loading.value = true
  try {
    const res = await getPagedFormList(params.pageNo, params.pageSize)
    if (res.code === 1) {
      papersMessage.value = {
        list: res.data.records.map(item => ({
          ...item,
          createdAt: formatCreatedAt(item.createdAt)
        })),
        total: res.data.total
      }
      params.total = res.data.total
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 格式化创建时间
const formatCreatedAt = (dateArray) => {
  if (Array.isArray(dateArray) && dateArray.length >= 6) {
    return `${dateArray[0]}-${String(dateArray[1]).padStart(2, '0')}-${String(dateArray[2]).padStart(2, '0')} ${String(dateArray[3]).padStart(2, '0')}:${String(dateArray[4]).padStart(2, '0')}`
  }
  return '无效日期'
}

// 新建空间
const handleAdd = () => {
  router.push('/main/team/addSpace')
}

// 编辑空间
const handleEdit = (row) => {

  router.push({ path: '/main/team/editspace', query: { id: row.id } })
}

// 打开重命名对话框
const handleRename = (row) => {
  currentRow.value = row
  renameForm.name = row.name || ''
  renameDialogVisible.value = true
}

// 确认重命名
const confirmRename = async () => {
  if (!renameForm.name.trim()) {
    ElMessage.warning('请输入空间名称')
    return
  }

  renameLoading.value = true
  try {
    const res = await updateFormName(currentRow.value.id, renameForm.name.trim())
    if (res.code === 1) {
      ElMessage.success('重命名成功')
      renameDialogVisible.value = false
      await queryFormMessage()
    } else {
      ElMessage.error(res.msg || '重命名失败')
    }
  } catch (error) {
    console.error('重命名失败:', error)
    ElMessage.error('重命名失败')
  } finally {
    renameLoading.value = false
  }
}

// 删除空间

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该空间吗？此操作不可恢复', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await deleteForm(row.id)
    if (res.code === 1) {
      ElMessage.success('删除成功')
      await queryFormMessage()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}


// 分页处理
const handleSizeChange = (val) => {
  params.pageSize = val
  queryFormMessage()
}

const handleCurrentChange = (val) => {
  params.pageNo = val
  queryFormMessage()
}

const tableRowClassName = () => {
  return 'table-row'
}

onMounted(() => {
  queryFormMessage()
})
</script>

<style scoped>
.space-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  width: 100%;
  max-width: 100%;
  overflow-x: hidden;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.title-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.icon {
  font-size: 24px;
  color: var(--el-color-primary);
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow-x: auto; /* 添加横向滚动 */
}

.name-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.name-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 500px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
  flex-wrap: nowrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 0 20px;
}

.table-row {
  cursor: pointer;
  transition: background-color 0.3s;
}

.table-row:hover {
  background-color: var(--el-table-row-hover-bg-color);
}

/* Element Plus 表格样式覆盖 */
:deep(.el-table) {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
  width: 100% !important;
}

:deep(.el-table__body-wrapper) {
  overflow-x: auto !important;
}

:deep(.el-button) {
  padding: 8px 16px;
  white-space: nowrap;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}

/* 适配移动设备 */
@media screen and (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 10px;
  }

  .operation-buttons {
    flex-direction: column;
    gap: 5px;
  }

  :deep(.el-button) {
    width: 100%;
  }
}

/* Safari 特定样式 */
@supports (-webkit-touch-callout: none) {
  .space-container {
    -webkit-overflow-scrolling: touch;
  }
}

/* Firefox 特定样式 */
@-moz-document url-prefix() {
  .table-container {
    scrollbar-width: thin;
    scrollbar-color: var(--el-color-primary) transparent;
  }
}

/* IE 和 Edge 特定样式 */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
  .space-container {
    display: flex;
    flex-direction: column;
  }
}
</style>
